<?php
namespace Admin\Controller;
//工具类
use Admin\Common\Tools as T;
//逻辑类
use Admin\Common\Logic;
use Admin\Common\Api\UserApi;
use Think\Controller;
use Think\Model;


/*require('/Admin/Common/Api/UserApi.class.php');*/

class BaseController extends Controller {
private $HAND_LOGINC   = null;


 protected function _initialize(){
    //初始化类
     $this->HAND_LOGINC = new Logic();
     // 获取当前用户ID
     $login  = new UserApi();
     
      // session('admin_user',null);
      // session('admin_user',array('id'=>'123','name'=>'admin','power'=>'all'));
     define('UID',$login->is_login());
     if( !UID ){// 还没登录 跳转到登录页面
         $this->redirect('Login/login');
     }
     $rule  = strtolower(CONTROLLER_NAME.'/'.ACTION_NAME);

     if($_GET['nav_id']!="" || $rule=='index/index'){
    //获取导航菜单
     $this->menu();
     //获取当前点击的菜单id
     $nav_id = empty($_GET['nav_id'])?47:$_GET['nav_id'];
     $this->parent_nav($nav_id);
     $this->one_nav($nav_id);
     //获取到该navid的父集
     $this->assign('navid',$nav_id); 
    }
  if( $_SESSION["admin_user"]['power'] !=strtolower('all')){
    // print_r( $auth_ruleStr=empty($_SESSION["admin_rules"])?"":$_SESSION["admin_rules"]);exit;
        // 判断权限
        if($this->checkUser()){
            if(IS_AJAX){
                $this->assign("message","找小宋来点权限！");
                $this->display('public/noauth');
                exit;
                // $this->ajaxreturn(array('state'=>0,'msg'=>"煞笔你没有权限，找小宋要点权限"));
            }else{
                $this->noauth("找小宋来点权限！");
            }
        } 
 }


     
   }



    /**
     * 权限验证方法
     * @param $uid
     * @return bool
     */
    public  function  checkUser(){
        //获取访问的控制器名称和方法名称
        $rule  = strtolower(CONTROLLER_NAME.'/'.ACTION_NAME);
        //获取登录用户的访问权限
        $auth_ruleStr=empty($_SESSION["admin_rules"])?"":$_SESSION["admin_rules"].','.strtolower('index/index');
        $flag=true;
        if (strpos(strtolower($auth_ruleStr),strtolower($rule)) !== false ){
            $flag=false;
        }
        if($_SESSION['admin_user']['power'] == 'all'){
            $flag=false;
        }
        return $flag;
    }

//获取菜单
 public  function menu(){
    //$id = isset(I('post.id')) ? I('post.id') : 0;
    $menu = $this->HAND_LOGINC->menu();
      
    // print_r($menu);exit;
    $this->assign('navlist',$menu);
  }


  //获取父集菜单
 public  function parent_nav($id){
    //$id = isset(I('post.id')) ? I('post.id') : 0;
    $menu = $this->HAND_LOGINC->parent_nav($id);
    // print_r($menu);exit;
    $this->assign('parent_nav',$menu);
  }

  //获取父集菜单
 public  function one_nav($id){
    //$id = isset(I('post.id')) ? I('post.id') : 0;
    $menu = $this->HAND_LOGINC->one_nav($id);
    // print_r($menu);exit;
    $this->assign('one_nav',$menu);
  }


      /**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @param type $model
     * @param type $map
     * @param type $sortBy
     * @param type $asc
     +----------------------------------------------------------
     */
    public function _list($model,$map,$sortBy='',$asc = false){
        //排序
        if(isset($_REQUEST['_order'])){
            $order = $_REQUEST['_order'];
        }else{
            $order = !empty($sortBy)?$sortBy:$model->getPk();
        }
        //排序方式，
        if(isset($_REQUEST["_sort"])){
            $sort = $_REQUEST["_sort"]?'asc':'desc';
        }else{
            $sort = $asc?'asc':'desc';
        }
        $voList = null;
        //取出满足条件的记录数据
        $count = $model->where($map)->count($model->getPk());
        if($count>0){
            //创建分页对象，是否设置行数
            if(!empty($_REQUEST['rows'])){
                $pageSize = $_REQUEST['rows'];
            }else{
                $pageSize = "10";
            }
            if(!empty($_REQUEST['page'])){
                $pageNow = $_REQUEST['page'];
            }else{
                $pageNow = "1";
            }
            $offset = $pageSize * ($pageNow - 1); //定义偏移量
            //分页查询出数据
            $voList = $model->where($map)->order($order." ".$sort)->limit($offset." , ".$pageSize)->select();

        }
        return array("total"=>$count,"rows"=>$voList);
    }



    /**
     * write by nirunfa 2015-08-07
     * update by 2015-12-19
     * @param $modelstr  模型字符或模型对象
     * @param $_where_order_field where条件,order排序,field查询字段 ,join联表查询数组,having 用于别名操作
     * @param string $count 查询条数字段
     */
    public function _getListsFromModel($modelstr,$_where_order_field=array(),$count='count(*) as tp_count'){
        
        $_where=$where=$_where_order_field['where'];
        $field=empty($_where_order_field['field'])?true:$_where_order_field['field'];
        $order=$_where_order_field['order'];
        $_join = $join = $_where_order_field['join'];
        $alias=$_where_order_field["alias"];
        $having = $_where_order_field['having'];
        $count_where=$_where_order_field['count_where'];
        $listrows=empty($_where_order_field['listrows'])?10:$_where_order_field['listrows'];
        $group=$_where_order_field["group"];
        $is_group_count = intval($_where_order_field['is_group_count']);

        $model = $modelstr;
        if(is_string($model)){
            $model=M($model);
        }

        //可以自定义内容 id
        $element_id = !empty($_where_order_field['id'])?$_where_order_field['id']:'order_list_item_content';
        if($is_group_count === 1){
            $_join = $_where_order_field['count_join'];
            $_where = $_where_order_field['count_where'];
        }

        $count_=$model->alias($alias)->where($_where)->join($_join)->field($count)->find();


        //总条数
        $sum =$count_['tp_count'];

        //当前页
        $current_page=I('request.p',1,'intval');

        //_page select跳转页数
        $_page=I('request._page');
        if(!empty($_page)){
            $current_page=$_page;
        }


        //总页数
        $pages=ceil($sum/$listrows);

        $limit=(($current_page-1)*$listrows).','.$listrows;

        $_lists = $model->alias($alias)->where($where)->join($join)->order($order)->field($field)->group($group)->having($having)->limit($limit)->select();


        if($pages<=5){
            for($i=1;$i<$pages+1;$i++){
            $options.="<option value='{$i}'>{$i}</option>";
            }
            /* $options.='<option value=\'2\'>2</option>
                       <option value=\'3\'>3</option>
                       <option value=\'4\'>4</option>
                       <option value=\'5\'>5</option>'; */
        }else{
            $options='<option value=\'1\'>1</option>';
            if($pages<=25){
                $options.='<option value=\'2\'>2</option>
                       <option value=\'3\'>3</option>
                       <option value=\'4\'>4</option>
                       <option value=\'5\'>5</option>';
                $options.="<option value='{$pages}'>{$pages}</option>";
            }else{
                $options.="<option value='25'>25</option>";
                if($pages>50){
                    $options.="<option value='50'>50</option>";
                }
                if($pages>75){
                    $options.="<option value='75'>75</option>";
                }

                $options.="<option value='{$pages}'>{$pages}</option>";
            }
        }

        $options=str_replace(">{$_page}<"," selected >{$_page}<",$options);

        $page_html="<table style='margin-bottom:25px;'><tbody><tr><td class='optd'>共<i class='blue'>{$sum}</i>条记录,&nbsp;当前显示第<i class='blue'>{$current_page}</i>页,&nbsp;";
        $page_html.="每页<input type='text'  style='width: 50px;min-height:15px;' value='{$listrows}' id='verypageshowcount' name='_listrows' class='verypageshowcount' onblur='inputGoToPage(this,\"{$element_id}\");' />.";
        $page_html.="跳转到第<select style='width: 45px;height: 25px;line-height: 25px;' name='gotoPage' class='gotoPage' id='gotoPage' onchange='selectGoToPage(this,\"{$element_id}\");'>{$options}</select></td>";

        $lis="<li class='pagination first_li first'><a href='{$this->url(1)}'onclick='return goPage(this,\"{$element_id}\");'>第一页</a></li>";

        $up_rows=$current_page-1;
        $lis.="<li class='pagination prev_li prev'><a href='{$this->url($up_rows)}'onclick='return goPage(this,\"{$element_id}\");'>上一页</a></li>";

        //显示范围
        $range=5;
        //数字连接
        $link_page = "";

        //第一页linenumber
        if($pages>$range && $current_page>=$range){
            $link_page.="<li class='pagination'><a href='{$this->url(1)}'onclick='return goPage(this,\"{$element_id}\");'>1</a></li>
            <li class='pagination more'><a href='javascript:;'>...</a></li>";
        }

        for($i = 1; $i <= $pages; $i++){
            $page = $i;

            //如果当前页小于每页显示范围
            //就相当于1-每页显示范围内条数，1 2 3至每页显示范围 ... 最后一页

            //如果当前页大于等于每页显示范围
            //就以每页显示范围为中心，1...前面两个+每页显示范围+后面两个...最后一页

            if($current_page<$range){
                if($page > 0 && $page != $current_page){
                    if($page <= $range){
                        $link_page .= "<li class='pagination '><a href='{$this->url($page)}' onclick='return goPage(this,\"{$element_id}\");'>{$page}</a></li>";
                    }else{
                        if(ceil($page)===$pages){
                            $link_page .='&nbsp;<li class="pagination more"><a href="javascript:;">...</a></li>';
                        }elseif($page>$pages){
                            break;
                        }else{
                            continue;
                        }
                    }
                }else{
                    if($page > 0 && $pages != 1){
                        $link_page .= "<li rhref='{$this->url($page)}' class='pagination current datalist_current_ahref'><a href='javascript:;'>{$page}</a></li>";
                    }
                }
            }else{
                if($page > 0 && $page != $current_page){
                    //这个情况处理特殊
                    //1.当前页是倒数第二页
                    //2.中间页数
                    //3.最后一页
                    //                        if($page+4>=$pages && $page==$current_page){
                    //                              continue;
                    //                        }

                    if(( ($page <= $current_page+2 && $page>=$current_page-2) ||
                        ($current_page+1==$pages && $page <= $current_page+1 && $page>=$current_page-3) ||
                        ($current_page==$pages && $page>=$current_page-4) ) ){
                        $link_page .= "<li class='pagination'><a href='{$this->url($page)}'onclick='return goPage(this,\"{$element_id}\");'>{$page}</a></li>";
                    }else{
                        if($page===1){
                            $link_page.='&nbsp;';
                        }elseif(ceil($page)===$pages){
                            $link_page .='<li class="pagination more"><a href="javascript:;">...</a></li>';
                        }elseif(ceil($page)>$pages){
                            break;
                        }else{
                            continue;
                        }
                    }
                }else{
                    if($page > 0 && $pages != 1){
                        $link_page .= "<li rhref='{$this->url($page)}' class='pagination current datalist_current_ahref'><a href='javascript:;'>{$page}</a></li>";
                    }
                }
            }
        }

        if($pages>$range && ($pages-$current_page)>5 ){
            $link_page.="<li class='pagination'><a href='{$this->url($pages)}'onclick='return goPage(this,\"{$element_id}\");'>{$pages}</a></li>";
        }


        $lis.=$link_page;

        $down_rows=($current_page+1)>$pages?0:($current_page+1);
        $lis.="<li class='pagination next_li next'><a href='{$this->url($down_rows)}'onclick='return goPage(this,\"{$element_id}\");'>下一页</a></li>";

        $lis.="<li class='pagination last_li last'><a href='{$this->url($pages)}' onclick='return goPage(this,\"{$element_id}\");'>最后一页</a></li>";

        $a_html="<td><ul class='paginList'>{$lis}</ul></td>";
        $page_html.=$a_html;

        $page_html.='</tr></tbody></table>';

        $page_data=array(
            'firstRow'=>(($current_page-1)*$listrows),
            'page'=>$current_page,
            'totalPages'=>$sum,
            'page_size'=>$listrows,
            'lists'=>$_lists,
            'page_html'=>$page_html, 
        );

        return $page_data;
    }



        /**
     * 生成链接URL
     * @param  integer $page 页码
     * @return string
     */
    private function url($page){
        if(empty($page)){
            return 'javascript:;';
        }
        $_post_query_data=(array)I('post.');
        $_get_query_data=(array)I('get.');
        $_query_data  = array_merge($_post_query_data,$_get_query_data);
        $_query_data['p']=$page;
        unset($_query_data['_page']);
        return U(ACTION_NAME, $_query_data);
    }
}
